package com.wechat.ferry.strategy.msg.receive;

import com.alibaba.fastjson2.JSONObject;
import com.wechat.ferry.entity.dto.WxPpMsgDTO;
import com.wechat.ferry.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class OrderMsgStrategy implements ReceiveMsgStrategy {

    private static final String ORDER_API_URL = "http://localhost:8080/api/wechat/message";

    @Override
    public String getStrategyType() {
        return "ORDER";
    }

    @Override
    public String doHandle(WxPpMsgDTO dto) {
        log.info("开始处理消息: {}", dto);
        // 检查消息内容是否符合订单格式
        if (isOrderMessage(dto.getContent())) {
            try {
                log.info("消息符合订单格式，开始构建消息对象");
                // 构建消息对象
                Map<String, Object> message = new HashMap<>();
                message.put("senderId", dto.getSender());
                message.put("receiverId", dto.getRoomId());
                message.put("content", dto.getContent());
                message.put("timestamp", dto.getTs() * 1000L); // 转换为毫秒
                message.put("messageType", "ORDER");
                
                // 解析订单内容
                Map<String, String> orderInfo = parseOrderContent(dto.getContent());
                message.put("orderId", orderInfo.get("orderId"));
                message.put("orderType", orderInfo.get("type"));
                message.put("orderAmount", orderInfo.get("totalPrice"));
                message.put("orderStatus", "PENDING");
                message.put("paymentMethod", "WECHAT");

                log.info("准备发送订单消息到API: {}", JSONObject.toJSONString(message));
                // 发送到API
                String response = HttpClientUtil.doPostJson(ORDER_API_URL, JSONObject.toJSONString(message));
                log.info("订单消息已转发到API，响应: {}", response);
                return response;
            } catch (Exception e) {
                log.error("处理订单消息时发生错误", e);
                return null;
            }
        }
        log.info("消息不符合订单格式: {}", dto.getContent());
        return null;
    }

    private boolean isOrderMessage(String content) {
        if (content == null) {
            log.info("消息内容为空，不符合订单格式");
            return false;
        }
        // 检查是否包含订单格式的关键字段，即使值为空也认为是订单消息
        boolean isOrder = content.contains("派单：") || 
               content.contains("接待：") || 
               content.contains("陪陪：") || 
               content.contains("老板：") || 
               content.contains("类型：") || 
               content.contains("时长：") || 
               content.contains("总价：");
        log.info("检查消息是否符合订单格式: {}, 结果: {}", content, isOrder);
        return isOrder;
    }

    private Map<String, String> parseOrderContent(String content) {
        log.info("开始解析订单内容: {}", content);
        Map<String, String> orderInfo = new HashMap<>();
        String[] lines = content.split("\n");
        for (String line : lines) {
            if (line.contains("：")) {
                String[] parts = line.split("：");
                if (parts.length == 2) {
                    String key = parts[0].trim();
                    String value = parts[1].trim();
                    log.info("解析订单字段: {} = {}", key, value);
                    switch (key) {
                        case "类型":
                            orderInfo.put("type", value);
                            break;
                        case "总价":
                            orderInfo.put("totalPrice", value);
                            break;
                    }
                }
            }
        }
        // 生成订单ID
        String orderId = "ORDER" + System.currentTimeMillis();
        orderInfo.put("orderId", orderId);
        log.info("订单内容解析完成: {}", orderInfo);
        return orderInfo;
    }
} 